import os

class Words(object):
    """
    Classe contennant un dictionnaire des mots retrouves, qui sert a associer aux
    mots leurs ids et leur frequence:
    
        {w1:[id,freq], ..., wn:[id,freq]}
    """
    def __init__(self):
        self.bag = {}
        
    def add(self, w, f):
        if self.bag.has_key(w):
            self.bag[w][1] += f
        else:
            self.bag[w] = [0, f]

    def addWords(self, words):
        for w in words:
            self.add(w, words[w])
    
    def prune(self, minFreq, maxFreq):
        bagTmp = self.bag.copy()
        counter = 0
        for i in bagTmp:
            if self.bag[i][1] > maxFreq or self.bag[i][1] < minFreq:
                self.bag.__delitem__(i)
            else:
                self.bag[i][0] = counter
                counter += 1
        del bagTmp        

            
    def save(self, minFreq, maxFreq):
        filename = 'words_' + minFreq.__str__() + '_' + maxFreq.__str__() + '.txt' 
        if filename not in os.listdir('.'):
            f = open(filename, 'w')
            for w in self.bag:
                f.write(w + ':' + self.bag[w].__str__() + '\n')
            f.close()
